package com.intxt.bbs.controller;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

import com.intxt.bbs.interceptor.UserLoginInterceptor;
import com.intxt.bbs.model.Link;
import com.intxt.bbs.model.User;
import com.intxt.bbs.model.UserGroup;
import com.intxt.bbs.service.LinkService;
import com.intxt.bbs.service.UserGroupService;
import com.intxt.bbs.service.UserService;
import com.intxt.bbs.util.Const;
import com.intxt.bbs.util.SimpleUtil;
import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.core.Controller;
import com.jfinal.ext.render.CaptchaRender;
import com.jfinal.log.Logger;
/**
 * 用户主要控制类
 * @author Administrator
 *
 */
@Before(UserLoginInterceptor. class)
public class UserController extends Controller {
	private Logger log = Logger.getLogger(TopicController.class);
	private static final UserService USER_SERVICE = new UserService();
	private static final UserGroupService USER_GROUP_SERVICE = new UserGroupService();
	private static final LinkService USER_LINK_SERVICE = new LinkService();
	public void index(){
		log.debug("--->进入USER控制<----");
		
	}
	/**
	 * 用户详情
	 */
	public void info(){
		log.debug("--->进入帖子详情---->");
		String userId = getPara("userId");

//		getSession().setAttribute("user", u);
		User u  = (User) getSession().getAttribute("user");
		if(userId!=null && userId.equals(u.getStr("id"))){//同一个人
			UserGroup ug = USER_GROUP_SERVICE.getUGById(u.getInt("user_group_id"));
			setAttr("userGroup", ug);
		}else{
			User userinfo = USER_SERVICE.getUserById(userId);
			
		}
		render("/user/info.jsp");
	}
	/**
	 * 更新基础信息
	 */
	public void updateBaseInfo(){
		log.debug("--->进入完善基础信息---->");
		setAttr("updateBaseInfo", "1");
		render("/user/updateInfo.jsp");
	}
	/**
	 * 更新头像
	 */
	public void updateHeadImg(){
		log.debug("--->进入更新头像---->");
		/*String imgUrl = getPara("imgUrl");
		Integer x = getParaToInt("x");
		Integer y = getParaToInt("y");
		Integer w = getParaToInt("w");
		Integer h = getParaToInt("h");
		
		
		if(StrKit.notNull(imgUrl)){
			ImageCut imageCut = new ImageCut();
			String imgPath = imageCut.cutImage("H:\\luna-SR1\\eclipse\\workspace_yime\\ext\\src\\main\\webapp\\img\\a.jpg", x, y, w, h);
			
			redirect("/bbs/userInfo");
		}else{
			setAttr("updateHeadImg", "1");
			render("/bbs/updateUserInfo.jsp");
		}*/
		setAttr("updateHeadImg", "1");
		render("/user/updateInfo.jsp");
	}
	
	public void updatePassword(){
		log.debug("--->进入更新密码---->");
		String oldPassword = getPara("oldPassword");
		if(oldPassword!=null){
			String newPassword = getPara("newPassword");
			User u  = (User)getSession().getAttribute("user");
			String password = u.get("password");
			if(oldPassword.equals(password)){
				u.set("password", newPassword);
				if(USER_SERVICE.updateUser(u)){
					redirect("/user/info");
					return ;
				}
			}
		}
		setAttr("updatePassword", "1");
		render("/user/updateInfo.jsp");
	}
	
	/**
	 * 注册提交
	 */
	public void reg(){
		String inputRandomCode = getPara("inputRandomCode");
        boolean loginSuccess = CaptchaRender.validate(this, inputRandomCode.toUpperCase(), Const.RANDOM_CODE_KEY);
        if (loginSuccess) { //验证码成功
    		String username = getPara("username");
    		String password = getPara("password1");
    		String email = getPara("email");
    		
    		User u = USER_SERVICE.reg(username, password, email,SimpleUtil.getRemoteAddress(getRequest()));
    		formateDate(u);
    		if(u!=null){
    			getSession().setAttribute("user", u);
    			redirect("/topic/list");
    			return;
    		}
        }
        	redirect("/register");
        
	}
	/**
	 * 登陆
	 */
	@ClearInterceptor
	public void login(){
		String inputRandomCode = getPara("code");
        boolean loginSuccess = CaptchaRender.validate(this, inputRandomCode.toUpperCase(), Const.RANDOM_CODE_KEY);
        if (loginSuccess) { //验证码成功
    		String username = getPara("username");
    		String password = getPara("password");
    		
    		User u = USER_SERVICE.login(username, password);
    		if(u!=null){
    			u.set("last_login_datetime", new Date());
    			USER_SERVICE.updateUser(u);
    			formateDate(u);
    			getSession().setAttribute("user", u);
    			UserGroup ug = USER_GROUP_SERVICE.getUGById(u.getInt("user_group_id"));
    			getSession().setAttribute("userGroup", ug);
    			List<Link> links = USER_LINK_SERVICE.findUserLink(u.getStr("id"));
    			getSession().setAttribute("userLinks", links);
    			
    			redirect("/topic");
    			return ;
    		}
        }
        redirect("/login");
	}
	
	/**
	 * 获取的时间格式不对 , 获取USER的时候处理一下
	 * @param u
	 */
	private void formateDate(User u){
		Date reg_date = u.getDate("reg_date");
		Date last_login_datetime = u.getDate("last_login_datetime");
		try {
			u.set("reg_date", SimpleUtil.formateDateTime(reg_date));
			u.set("last_login_datetime", SimpleUtil.formateDateTime(last_login_datetime));
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}
